package com.hwhhhh.mygrad;

import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.hwhhhh.mygrad.adapter.CommentAdapter;
import com.hwhhhh.mygrad.api.Api;
import com.hwhhhh.mygrad.api.ApiCallback;
import com.hwhhhh.mygrad.api.ApiConfig;
import com.hwhhhh.mygrad.dto.Appointment;
import com.hwhhhh.mygrad.dto.ClsDTO;
import com.hwhhhh.mygrad.dto.CommentDTO;
import com.hwhhhh.mygrad.dto.FreeClsDTO;
import com.hwhhhh.mygrad.entity.RespData;
import com.hwhhhh.mygrad.fragment.BottomHintFragment;
import com.hwhhhh.mygrad.fragment.ClsEditFragment;
import com.hwhhhh.mygrad.interfaces.CommentListener;
import com.hwhhhh.mygrad.utils.StringUtils;
import com.hwhhhh.mygrad.view.IconfontView;

import java.util.Date;
import java.util.HashMap;

public class ClsInfoActivity extends BaseActivity implements BottomHintFragment.BottomHintCallBack {
    private TextView tvClsInfoNum, tvClsInfoAppoint, tvClsInfoOccupy, tvClsInfoCapacity, tvClsInfoCalendar;
    private Button btnCollect, btnAppoint, btnOccupy;
    private IconfontView icClsInfoCalendar, icBack;
    private RecyclerView rvComment;
    private int page;
    private ClsDTO clsDTO;
//    private FreeClsDTO entity;
    private int freeClsId, clsId;
    private EditText etClsComment, etSearch;
    private CommentAdapter commentAdapter;

    @Override
    protected void initView() {
        tvClsInfoNum = findViewById(R.id.tv_cls_info_num);
        tvClsInfoAppoint = findViewById(R.id.tv_cls_info_appoint);
        tvClsInfoOccupy = findViewById(R.id.tv_cls_info_occupy);
        tvClsInfoCapacity = findViewById(R.id.tv_cls_info_capacity);
        tvClsInfoCalendar = findViewById(R.id.tv_cls_info_calender);
        btnCollect = findViewById(R.id.btn_collect);
        icClsInfoCalendar = findViewById(R.id.ic_cls_info_calendar);
        icBack = findViewById(R.id.ic_cls_info_back);

        etClsComment = findViewById(R.id.et_cls_comment);
        etSearch = findViewById(R.id.et_cls_info_search);
        rvComment = findViewById(R.id.rv_comment);
        btnAppoint = findViewById(R.id.btn_appoint);
        btnOccupy = findViewById(R.id.btn_occupy);
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_cls_info;
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void initData() {
        // 获取教室信息
        Intent in = getIntent();
//        entity = (FreeClsDTO) in.getSerializableExtra("cls");
        freeClsId = in.getIntExtra("freeClsId", 1);
        clsId = in.getIntExtra("clsId", 1);
        requestData();
        String date = in.getStringExtra("date");

        tvClsInfoCalendar.setText(date);
        icBack.setOnClickListener(v -> { finish(); });
        btnCollect.setOnClickListener(v -> {
            btnCollectIsCollected(!clsDTO.isCollected());
            clsDTO.setCollected(!clsDTO.isCollected());
        });
        etClsComment.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                etClsComment.clearFocus();
                showCommentFragment(freeClsId, 0, null) // here
                        .setCommentListener(new CommentListener() {
                            @Override
                            public void onSuccess(CommentDTO c) {
                                ClsInfoActivity.this.runOnUiThread(() -> {
                                    showToast("评论成功！积分+1");
                                    commentAdapter.insertTo(0, c);
                                    commentAdapter.notifyItemInserted(0);
                                });
                            }

                            @Override
                            public void onFail() {

                            }
                        });
            }
        });
        etSearch.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                etSearch.clearFocus();
                navigateTo(SearchActivity.class);
            }
        });
        btnOccupy.setOnClickListener(v -> {
            if (clsDTO.getAppointment().getState() == 0 || clsDTO.getAppointment().getState() == -1 || clsDTO.getAppointment().getState() == 2) {   // 状态：已经预订/未预订/预订结束 》》 占用
                btnAppoint.setEnabled(false);
                HashMap<String, Object> params = new HashMap<>();
                params.put("id", clsDTO.getAppointment().getId());
                params.put("appoint", clsDTO.getAppointment().getState() != -1 && clsDTO.getAppointment().getState() != 2);
                params.put("freeClsId", freeClsId);// here
                Api.config(ApiConfig.OCCUPY, params).postRequest(this, new ApiCallback() {
                    @Override
                    public void onSuccess(String res) {
                        RespData<Appointment> data = StringUtils.fromJson(res, new TypeToken<RespData<Appointment>>(){}.getType());
                        if (data.getCode() == 200) {
                            ClsInfoActivity.this.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    setBtnAppointAndOccupy(1);
                                    clsDTO.setAppointment(data.getData());
                                    btnAppoint.setEnabled(true);
                                }
                            });
                        }
                    }

                    @Override
                    public void onFailure(Exception e) {
                        Looper.prepare();
                        btnAppoint.setEnabled(true);
                        Looper.loop();
                    }
                });
            } else if (clsDTO.getAppointment().getState() == 1){
                btnAppoint.setEnabled(false);
                Api.config(ApiConfig.OCCUPY + "/" + clsDTO.getAppointment().getId(), null).putRequest(this, new ApiCallback() {
                    @Override
                    public void onSuccess(String res) {
                        RespData<Appointment> data = StringUtils.fromJson(res, new TypeToken<RespData<Appointment>>(){}.getType());
                        if (data.getCode() == 200) {
                            ClsInfoActivity.this.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    setBtnAppointAndOccupy(2);
                                    clsDTO.setAppointment(data.getData());
                                    btnAppoint.setEnabled(true);
                                }
                            });
                        }

                    }

                    @Override
                    public void onFailure(Exception e) {
                        Looper.prepare();
                        btnAppoint.setEnabled(true);
                        Looper.loop();
                    }
                });
            }
        });
        btnAppoint.setOnClickListener(v -> {
            if (clsDTO.getAppointment().getState() == -1 || clsDTO.getAppointment().getState() == 2) {   // 未预订状态，此时进入预订状态。
                btnAppoint.setEnabled(false);
                Api.config(ApiConfig.MAKE_APPOINTMENT +"/" + freeClsId, null).postRequest(this, new ApiCallback() {
                    @Override
                    public void onSuccess(String res) {
                        RespData<Appointment> data = StringUtils.fromJson(res, new TypeToken<RespData<Appointment>>(){}.getType());
                        if (data.getCode() == 200) {
                            ClsInfoActivity.this.runOnUiThread(() -> {
                                setBtnAppointAndOccupy(0);
                                clsDTO.setAppointment(data.getData());
                                btnAppoint.setEnabled(true);
                            });
                        }
                    }

                    @Override
                    public void onFailure(Exception e) {
                        Looper.prepare();
                        btnAppoint.setEnabled(true);
                        Looper.loop();
                    }
                });
            } else {
                btnAppoint.setEnabled(false);
                Api.config(ApiConfig.CANCEL_APPOINTMENT + "/" + clsDTO.getAppointment().getId(), null).putRequest(this, new ApiCallback() {
                    @Override
                    public void onSuccess(String res) {
                        RespData<Appointment> data = StringUtils.fromJson(res, new TypeToken<RespData<Appointment>>(){}.getType());
                        if (data.getCode() == 200) {
                            ClsInfoActivity.this.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    setBtnAppointAndOccupy(-1);
                                    clsDTO.setAppointment(data.getData());
                                    btnAppoint.setEnabled(true);
                                }
                            });
                        }
                    }

                    @Override
                    public void onFailure(Exception e) {
                        Looper.prepare();
                        btnAppoint.setEnabled(true);
                        Looper.loop();
                    }
                });
            }
        });
    }

    private void requestData() {
        // 请求评论区信息
        HashMap<String, Object> params = new HashMap<>();
        params.put("id", freeClsId);
        params.put("page", page);
        params.put("clsId", clsId);
        Api.config(ApiConfig.CLS_INFO, params).getRequest(this, new ApiCallback() {
            @SuppressLint("SetTextI18n")
            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onSuccess(String res) {
                RespData<ClsDTO> data = StringUtils.fromJson(res, new TypeToken<RespData<ClsDTO>>(){}.getType());
                if (data.getCode() == 200) {
                    clsDTO = data.getData();
                    ClsInfoActivity.this.runOnUiThread(() -> {
                        // 设置收藏按键
                        if (clsDTO.isCollected()) btnCollectIsCollected(true);
                        if (clsDTO.getAppointment().getState() == 0) { // 已预订
                            btnAppoint.setText("取消预订");
                            ViewGroup.LayoutParams layoutParams1 = btnAppoint.getLayoutParams();
                            layoutParams1.width = 225;
                            btnAppoint.setLayoutParams(layoutParams1);
                        } else if (clsDTO.getAppointment().getState() == 1){
                            btnOccupy.setText("停止占用");
                            btnAppoint.setVisibility(View.GONE);
                            // 改变宽度得这样才行
                            btnOccupy.getLayoutParams().width = 225;
                        }
                        // 评论区
                        commentAdapter = new CommentAdapter(ClsInfoActivity.this, clsDTO.getCommentDTOList());
                        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(ClsInfoActivity.this);
                        rvComment.setAdapter(commentAdapter);
                        rvComment.setLayoutManager(linearLayoutManager);
                        FreeClsDTO entity = clsDTO.getFreeClassroom();
                        // 设置教室信息相关控件
                        tvClsInfoNum.setText(entity.getClassroomNum());
                        tvClsInfoAppoint.setText(Integer.toString(entity.getAppointNum()));
                        tvClsInfoOccupy.setText(Integer.toString(entity.getOccupyNum()));
                        tvClsInfoCapacity.setText(Integer.toString(entity.getCapacity()));
                    });
                } else {
                    showToastSync(data.getMsg());
                }
            }

            @Override
            public void onFailure(Exception e) {
                showToastSync("request fail");
            }
        });

    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void btnCollectIsCollected(boolean isCollected) {
        if (!isCollected) {
            btnCollect.setBackground(getDrawable(R.drawable.bg_uncollect_btn));
            String str = "收藏教室";
            btnCollect.setText(str);
        } else {
            btnCollect.setBackground(getDrawable(R.drawable.bg_collected_btn));
            String str = "已收藏";
            btnCollect.setText(str);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void setBtnAppointAndOccupy(int state) {
        switch (state) {
            case -1:    // 状态：未预订。  进入此状态时，预订状态0 》》 没有预订-1
                btnAppoint.setText("预订");
                ViewGroup.LayoutParams layoutParams = btnAppoint.getLayoutParams();
                layoutParams.width = 150;
                btnAppoint.setLayoutParams(layoutParams);
                showToast("取消预订成功！");
                break;
            case 0:     // 状态：已经预订。 进入此状态时，没有预订-1 》》 预订0
                btnAppoint.setText("取消预订");
                ViewGroup.LayoutParams layoutParams1 = btnAppoint.getLayoutParams();
                layoutParams1.width = 225;
                btnAppoint.setLayoutParams(layoutParams1);
                showToast("预订成功！记得及时来哦~");
                break;
            case 1:     // 状态：正在占用。  进入此状态时，未占用0或-1 》》 占用1
                btnOccupy.setText("停止占用");
                if (clsDTO.getAppointment().getState() == 0) {
                    btnAppoint.setText("预订");
                    btnAppoint.getLayoutParams().width = 150;
                }
                btnAppoint.setVisibility(View.GONE);
                // 改变宽度得这样才行
                btnOccupy.getLayoutParams().width = 225;
                showToast("占用成功！认真学习吧~");
                break;
            case 2:     // 状态：停止占用。  进入此状态：正在占用1 》》 停止占用2
                btnAppoint.setVisibility(View.VISIBLE);
                btnOccupy.setText("占用");
                btnOccupy.getLayoutParams().width = 150;
                showToast("停止占用成功！快休息下~");
                break;
        }
    }

    @Override
    public void doPositive(int position, int requestCode) {
        showToast("nihao");
    }

    @Override
    public void doNegative(int requestCode) {
        if (requestCode == 203) {
            BottomHintFragment bottomHintFragment = (BottomHintFragment) getSupportFragmentManager().findFragmentByTag(BottomHintFragment.class.getSimpleName());
            if (bottomHintFragment != null) {
                bottomHintFragment.dismiss();
            }
        }
    }
}